﻿using System;
using System.Data;
using System.Globalization;
using System.Linq;
using System.Web.UI;
using System.Web.UI.HtmlControls;
using System.Web.UI.WebControls;
using Pantry.Commons;
using Pantry.Business;

namespace Pantry.Web.Users.Controls
{

    public partial class ListOrganization : System.Web.UI.UserControl
    {
        private readonly IFormatProvider _formatProvider = CultureInfo.CurrentCulture;
        private ServiceBus _serviceBus;
        private OrganizationBus _organizationBus;
        private RoleBus _roleBus;
        private static bool _isSorted;
        private DataView _dataView;
        protected void Page_Load(object sender, EventArgs e)
        {
            LoadOrganization();
        }
        #region Methods
        /// <summary>
        /// Loads the organization.
        /// </summary>
        private void LoadOrganization()
        {
            if (!string.IsNullOrEmpty(Request.QueryString["id"]))
            {
                int seviceId = int.Parse(Request.QueryString["id"], _formatProvider);
                _organizationBus = new OrganizationBus();
                DataTable dataTable = _organizationBus.ListOrganizationRole(seviceId);
                _dataView = dataTable.DefaultView;
                CollectionPager1.PageSize = 10;
                CollectionPager1.BindToControl = RepeaterOrganization;
                CollectionPager1.DataSource = _dataView;
                RepeaterOrganization.DataSource = CollectionPager1.DataSourcePaged;
                RepeaterOrganization.DataBind();
            }
        }
        /// <summary>
        /// Lists the role.
        /// </summary>
        private void ListRole()
        {
            _roleBus = new RoleBus();
            var dataView = _roleBus.ListRole().DefaultView;
            RepeaterRole.DataSource = dataView;
            RepeaterRole.DataBind();
        }
        /// <summary>
        /// Saves the organization role.
        /// </summary>
        private void SaveOrganizationRole()
        {
            try
            {
                if (HiddenFieldOrganizationId.Value != null)
                {
                    _organizationBus = new OrganizationBus();
                    int organizationId = int.Parse(HiddenFieldOrganizationId.Value, _formatProvider);
                    bool isDelete = _organizationBus.DeleteAllOrganizationRole(organizationId);
                    foreach (RepeaterItem item in RepeaterRole.Items)
                    {
                        var checkbox = item.FindControl("checkboxRole") as HtmlInputCheckBox;
                        if (checkbox != null && checkbox.Checked)
                        {
                            int roleId = int.Parse(checkbox.Value, _formatProvider);
                            bool result = _organizationBus.UpdateOrganizationRole(organizationId, roleId);
                            ScriptManager.RegisterStartupScript(UpdatePanelRole, GetType(), "close", "CloseRolePopup()", true);
                            ScriptManager.RegisterStartupScript(UpdatePanelRole, GetType(), "MyKey",
                                                                           result
                                                                               ? "showmessage('Successfully !','SUCCESS','','false');"
                                                                               : "showmessage('Failed! !','ERROR','','false');",
                                                                           true);
                        }
                        else
                        {
                            ScriptManager.RegisterStartupScript(UpdatePanelRole, GetType(), "close", "CloseRolePopup()", true);
                        }
                    }
                    ScriptManager.RegisterStartupScript(UpdatePanelRole, GetType(), "MyKey",
                                                                           isDelete
                                                                               ? "showmessage('Successfully !','SUCCESS','','false');"
                                                                               : "showmessage('Failed! !','ERROR','','false');",
                                                                           true);
                }
                LoadOrganization();
            }
            catch (ArgumentNullException exception)
            {
                ExceptionHandler.WriteErrorLog(exception);
            }
            catch (ArgumentException exception)
            {
                ExceptionHandler.WriteErrorLog(exception);
            }
        }
        /// <summary>
        /// Marks the sevice in active.
        /// </summary>
        
        private void Sorting(string field)
        {
            try
            {
                if (_isSorted)
                {
                    _dataView.Sort = string.Format(_formatProvider, "{0} DESC", field);
                    _isSorted = false;
                }
                else
                {
                    _dataView.Sort = string.Format(_formatProvider, "{0} ASC", field);
                    _isSorted = true;
                }
            }
            catch (Exception exception)
            {
                ExceptionHandler.WriteErrorLog(exception);
            }
        }
        #endregion

        #region Event Handler
        /// <summary>
        /// Edits the role popup click.
        /// </summary>
        /// <param name="sender">The sender.</param>
        /// <param name="e">The <see cref="System.EventArgs"/> instance containing the event data.</param>
        protected void EditRolePopupClick(object sender, EventArgs e)
        {
            ListRole();
            var linkButton = (LinkButton)sender;
            string argument = linkButton.CommandArgument;
            var splitArgument = argument.Split('$');
            HiddenFieldOrganizationId.Value = splitArgument[0].Trim();
            var values = splitArgument[1].Split(',');
            foreach (var checkbox in from t in values from RepeaterItem item in RepeaterRole.Items let checkbox = item.FindControl("checkboxRole") as HtmlInputCheckBox where checkbox != null && t.Trim() == checkbox.Value select checkbox)
            {
                checkbox.Checked = true;
            }
            foreach (RepeaterItem item in RepeaterRole.Items)
            {
                var checkbox = item.FindControl("checkboxRole") as HtmlInputCheckBox;
                var literal = item.FindControl("textRoleName") as Literal;
                foreach (string t in values)
                {
                    if (literal != null && literal.Text == t.Trim())
                    {
                        if (checkbox != null) checkbox.Checked = true;
                    }
                }
            }
            ScriptManager.RegisterStartupScript(UpdatePanelRole, GetType(), "Key", "OpenRolePopup()", true);
        }
        protected void ButtonSaveClick(object sender, EventArgs eventArgs)
        {
            SaveOrganizationRole();
        }
        protected void LinkButtonOrganizationNameClick(object sender, EventArgs e)
        {
            Sorting("OrganizationName");
        }
        protected void LinkButtonDescriptionClick(object sender, EventArgs e)
        {
            Sorting("ShortDescription");
        }
        protected void LinkButtonListRoleClick(object sender, EventArgs e)
        {
            Sorting("ListRole");
        }
        #endregion

    }
}